#==================================================
#	Run
#==================================================
# 移动
#==================================================
# @datetime: 2021-12-22 13:59:56
#==================================================

extends "res://addons/function_tree/src/base/function/statemachineroot/State.gd"


var target_pos : Vector2
var move_to
var t = 0


#(override)
func _init_node():
	._init_node()
	move_to = get_function("MoveTo")


#(override)
func enter(pos: Vector2):
	target_pos = pos
	if !get_function("General").has_road():
		# 如果移动方向已经没有路了
		switch_dir()
		print("没路了，开始从", host.global_position, "移动到", target_pos)
	move_to.control(pos)

#(override)
func exit():
	move_to.stop()
	t = 0

#(override)
func state_process(delta):
	t -= delta
	# 没路或撞墙
	if (not get_function("General").has_road()
		|| host.is_on_wall()
	):
		switch_dir()
	# 存在攻击目标
	elif get_custom_data()["AttackTarget"]:
		switch_to("Attack")


##  切换方向
func switch_dir():
	if t <= 0:
		# 切换间隔时间不能超过 0.1 秒
		t = 0.1
		# 剩余距离
		var dist = max(100, abs(target_pos.x - host.global_position.x))
		# 切换方向
		target_pos.x = host.global_position.x + dist * -property.face_dir.x
		move_to.control(target_pos)


func _on_MoveTo_arrived():
	if get_parent().get_current_state() == self:
		switch_to("Idle")
